package com.zjh.admin.sys.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zjh.admin.sys.model.ResourceEntity;
import com.zjh.admin.sys.service.ResourceService;
import com.zjh.admin.sys.service.RoleResourceService;
import com.zjh.common.constants.Common;
import com.zjh.common.dtgrid.model.Pager;
import com.zjh.common.model.JSTreeEntity;
import com.zjh.common.model.Select2Entity;
import com.zjh.common.result.Result;
import com.zjh.common.util.PageUtil;
import com.zjh.common.util.TreeUtil;
import com.zjh.core.base.basecontroller.BaseController;
import com.zjh.core.exception.AjaxException;
import com.zjh.core.exception.SystemException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author ZWX
 * @Description: 资源controller
 * @date 2018/10/15 23：28
 */
@Controller
@RequestMapping("/resource/")
public class ResourceController extends BaseController {

    @Autowired
    private ResourceService resourceService;

    @Autowired
    private RoleResourceService roleResourceService;

    /**
     * list跳转
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("listUI.html")
    public String listUI(Model model, HttpServletRequest request) {
        try {
            PageUtil page = new PageUtil();
            if (request.getParameterMap().containsKey("page")) {
                setPage(request, page);
            }
            model.addAttribute("page", page);
            return Common.BACKGROUND_PATH + "/sys/resource/list";

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }


    /**
     * ajax分页查询资源信息
     *
     * @param gridPager
     * @return
     */
    @PostMapping(value = "list.html")
    @ResponseBody
    public Object list(String gridPager) {
        Map<String, Object> parameters = null;
        // 映射Pager对象
        Pager pager = JSON.parseObject(gridPager, Pager.class);
        // 判断是否包含自定义参数
        parameters = pager.getParameters();
        if (parameters.size() < 0) {
            parameters.put("name", null);
        }
        // 设置分页，page里面包含了分页信息
        Page<Object> page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize(), true);

        List<ResourceEntity> list = resourceService.queryListByPage(parameters);
        parameters.clear();
        setPageList(parameters, pager, page, list);
        return parameters;
    }


    /**
     * listGrid跳转
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("listGridUI.html")
    public String listTreeUI(Model model, HttpServletRequest request) {
        try {
            PageUtil page = new PageUtil();
            if (request.getParameterMap().containsKey("page")) {
                setPage(request, page);
            }
            model.addAttribute("page", page);
            return Common.BACKGROUND_PATH + "/sys/resource/listGrid";

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }


    /**
     * ajax分页查询资源树信息
     *
     * @param gridPager
     * @return
     */
    @RequestMapping("listGrid.html")
    @ResponseBody
    public Object listTree(String gridPager) {
        Map<String, Object> parameters = null;
        // 映射Pager对象
        Pager pager = JSON.parseObject(gridPager, Pager.class);
        // 判断是否包含自定义参数
        parameters = pager.getParameters();
        if (parameters.size() < 0) {
            parameters.put("name", null);
            parameters.put("parentId", null);
        } else if (!parameters.containsKey("name")) {
            parameters.put("name", null);
        }

        Page<Object> page = null;
        if (null == parameters.get("parentId") || "".equals(parameters.get("parentId"))) {
            // 设置分页，page里面包含了分页信息
            page = PageHelper.startPage(pager.getNowPage(), pager.getPageSize(), true);
        }

        List<ResourceEntity> list = resourceService.queryTreeGridListByPage(parameters);
        parameters.clear();
        parameters.put("isSuccess", Boolean.TRUE);
        if (null != page) {
            parameters.put("nowPage", pager.getNowPage());
            parameters.put("pageSize", pager.getPageSize());
            parameters.put("pageCount", page.getPages());
            parameters.put("recordCount", page.getTotal());
            parameters.put("startRecord", page.getStartRow());
        }
        //列表展示数据
        parameters.put("exhibitDatas", list);
        return parameters;
    }

    /**
     * 查询点击父资源的子资源信息
     *
     * @return
     */
    @RequestMapping("withoutAuth/resourceSelectTree.html")
    @ResponseBody
    public Object resourceSelectTree() {
        List<Select2Entity> select2Entity = null;
        try {
            Map<String, Object> parameter = new HashMap<>(16);
            List<ResourceEntity> list = resourceService.queryListByPage(parameter);
            select2Entity = new TreeUtil().getSelectTree(list, null);
            parameter.clear();
            parameter.put("items", select2Entity);
            return parameter;

        } catch (Exception e) {
            throw new AjaxException(e);
        }
    }

    /**
     * add跳转
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("addUI.html")
    public String addUI(Model model, HttpServletRequest request) {
        try {
            List<ResourceEntity> list = resourceService.queryListByPage(new HashMap<String, Object>());
            List<Select2Entity> select2List = new TreeUtil().getSelectTree(list, null);
            model.addAttribute("select2List", select2List);
            return Common.BACKGROUND_PATH + "/sys/resource/form";

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 添加资源
     *
     * @param resourceEntity
     * @return
     */
    @RequestMapping("add.html")
    @ResponseBody
    public Result add(ResourceEntity resourceEntity) {
        Result result = new Result();
        try {
            if (resourceEntity.getParentId() == 0){
                resourceEntity.setParentId(null);
            }
            resourceEntity.setIsHide(0);
            resourceEntity.setCreateTime(new Date(System.currentTimeMillis()));
            resourceEntity.setSourceKey(resourceEntity.getSourceKey().trim());
            resourceEntity.setSourceUrl(resourceEntity.getSourceUrl().trim());
            boolean status = roleResourceService.insertRoleAndResource(resourceEntity);
            if (status) {
                result.success("添加成功");
            } else {
                result.error("添加失败");
            }

        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * icon跳转
     *
     * @return
     */
    @RequestMapping("withoutAuth/icon.html")
    public String icon() {
        return Common.BACKGROUND_PATH + "/sys/resource/icon";
    }

    /**
     * edit跳转
     *
     * @param model
     * @param request
     * @param id
     * @return
     */
    @RequestMapping("editUI.html")
    public String editUI(Model model, HttpServletRequest request, Long id) {
        try {
            ResourceEntity resourceEntity = resourceService.findById(id);
            PageUtil page = new PageUtil();
            setPage(request, page);

            List<ResourceEntity> list = resourceService.queryListByPage(new HashMap<String, Object>());
            List<Select2Entity> select2List = new TreeUtil().getSelectTree(list, null);

            model.addAttribute("page", page);
            model.addAttribute("resourceEntity", resourceEntity);
            model.addAttribute("select2List", select2List);
            return Common.BACKGROUND_PATH + "/sys/resource/form";

        } catch (Exception e) {
            throw new SystemException(e);
        }
    }

    /**
     * 修改资源
     *
     * @param resourceEntity
     * @return
     */
    @RequestMapping("edit.html")
    @ResponseBody
    public Result update(ResourceEntity resourceEntity) {
        Result result = new Result();
        try {
            if (resourceEntity.getType() == 1) {
                resourceEntity.setIcon(null);
            }
            if (resourceEntity.getParentId() == 0){
                resourceEntity.setParentId(null);
            }
            int status = resourceService.update(resourceEntity);
            if (status > 0) {
                result.success("编辑成功");
            } else {
                result.error("编辑失败");
            }
        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 删除资源
     *
     * @param ids
     * @return
     */
    @RequestMapping("deleteBatch.html")
    @ResponseBody
    public Result deleteBatch(String ids) {
        Result result = new Result();
        try {
            String[] roleIds = ids.split(",");
            List<Long> list = new ArrayList<>();
            for (String string : roleIds) {
                list.add(Long.valueOf(string));
            }
            boolean flag = resourceService.deleteRoleAndResource(list);
            if (flag) {
                result.success("删除成功");
            } else {
                result.error("删除失败");
            }

        } catch (Exception e) {
            throw new AjaxException(e);
        }
        return result;
    }

    /**
     * 验证是否存在相同资源id
     *
     * @param resourceId
     * @return
     */
    @RequestMapping("withoutAuth/validateResource.html")
    @ResponseBody
    public Result validateResource(Integer resourceId) {
        Result result = new Result();
        try {
            Map<String, Object> param = new HashMap<>(16);
            param.put("id", resourceId);
            int count = resourceService.count(param);
            if (count > 0) {
                result.success();
            } else {
                result.error();
            }
            return result;
        } catch (Exception e) {
            throw new AjaxException(e);
        }
    }

    /**
     * 查询资源树信息
     * @param roleId
     * @return
     */
    @RequestMapping("withoutAuth/resourceTree.html")
    @ResponseBody
    public Object resourceTree(int roleId) {
        Map<String,Object> parameter = new HashMap<>(16);
        List<JSTreeEntity> jstreeList = null;
        try {
            parameter.put("isHide", 0);
            //parameter.put("type", 0);
            parameter.put("roleId", roleId);
            List<ResourceEntity> list = resourceService.queryResourceList(parameter);
            jstreeList = new TreeUtil().generateJSTree(list);
        }
        catch (Exception e) {
            jstreeList = new ArrayList<>();
            logger.error(e.getMessage(), e);
        }
        return jstreeList;
    }

}
